//
//  WKHomeViewController.swift
//  WKweiBo
//
//  Created by 阿拉斯加的狗 on 15/12/6.
//  Copyright © 2015年 阿拉斯加的🐶. All rights reserved.
//

import UIKit
import SVProgressHUD
//可重用ID标示符
let StatusCellNormalId = "StatusCellNormalId"
/// 转发微博的可重用 ID
let StatusCellRetweetedId = "StatusCellRetweetedId"

class WKHomeViewController: WKVisitorViewController {

    //定义一个微博数据列表模型
    private lazy var listViewModel = StatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置页面
        if !UserAccountViewModel.sharedUserAccount.userLogin {
        
            visitor?.setupInfo(nil, title: "关注一些人，回这里看看有什么惊喜")
            
            return
            
        }
        
        //准备表格
        prepareTableView()
        
        //准备数据
        loadData()
        
        //注册通知
        NSNotificationCenter.defaultCenter().addObserverForName(WKStatusSelectedPhotoNotification, object: nil, queue: nil) { [weak self] (n) -> Void in
            
            guard let indexPath = n.userInfo?[WKStatusSelectedPhotoIndexPathKey] as? NSIndexPath else {
            
                return
            }
            
            guard let urls = n.userInfo?[WKStatusSelectedPhotoURLsKey] as? [NSURL] else {
            
                return
            }
            
            //设置代理
            guard let cell = n.object as? PhotoBrowserPresentDelegate else {
            
                return
            }
            
            let vc = PhotoBrowserViewController(urls: urls, indexPath: indexPath)
            
            //自定义转场动画
            vc.modalPresentationStyle = UIModalPresentationStyle.Custom
            
            //设置动画代理
            vc.transitioningDelegate = self?.photoBrowserAnimator
            
            //设置动画代理参数
            self?.photoBrowserAnimator.setDelegateParams(cell, indexPath: indexPath, dismissDelegate: vc)
            
            //Modal 
            self?.presentViewController(vc, animated: true, completion: nil)
            
        }
        
        
    }

    //注销通知
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }
    
    //准备表格
    private func prepareTableView () {
    
        //注册可重用ID
        tableView.registerClass(StatusRetweetedCell.self, forCellReuseIdentifier: StatusCellRetweetedId)
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: StatusCellNormalId)
        
        //取消分割线
        tableView.separatorStyle = .None
        
        //设置一个预估高度
        tableView.estimatedRowHeight = 400
        
        //刷新控件
        refreshControl = WKRefreshControl()
        
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        //设置上拉刷新控件
        tableView.tableFooterView = pullupView
        
    }
    
   
    //加载数据
   @objc private func loadData() {
    
        refreshControl?.beginRefreshing()
    

    
        listViewModel.loadStatus (isPullup: pullupView.isAnimating()){ (isSuccessed) -> () in
            if !isSuccessed {
                SVProgressHUD.showInfoWithStatus("加载数据出错,请从新加载")
                return
            }
            
            //停止刷新
            self.refreshControl?.endRefreshing()
            
            //关闭上拉刷新控件动画
           self.pullupView.stopAnimating()
            
            //显示下拉刷新控件
            self.showPulldownTip()
            
            //刷新数据
            self.tableView.reloadData()
        }
    }
    
    //显示下拉刷新
    private func showPulldownTip() {
    
        guard let count = listViewModel.pulldownCount else {
        
            return
        }
    
        pulldownTipLabel.text = (count == 0) ? "没有新微博" : "刷新到\(count)条微博"
        
        let height: CGFloat = 44
        let rect = CGRect(x: 0, y: 0, width: view.bounds.width, height: height)
        pulldownTipLabel.frame = CGRectOffset(rect, 0, -2 * height)
        
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            self.pulldownTipLabel.frame = CGRectOffset(rect, 0, height)
            }) { (_) -> Void in
                
            UIView.animateWithDuration(1.0, animations: { () -> Void in
                self.pulldownTipLabel.frame = CGRectOffset(rect, 0, -2 * height)
            })
        }
        
        
    }
    
    
    //懒加载 上啦刷新控件
    private lazy var pulldownTipLabel:UILabel = {
    
        let label = UILabel(title: "", color: UIColor.whiteColor(), fontSize: 18)
        label.backgroundColor = UIColor.orangeColor()
        
        //添加到navigationBar上
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        return label
    
    }()
    
    
    private lazy var pullupView: UIActivityIndicatorView = {
    
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        indicator.color = UIColor.lightGrayColor()
        
        return indicator
    
    }()
    
    //懒加载转场动画代理
    private lazy var photoBrowserAnimator: PhotoBrowserAnimator = PhotoBrowserAnimator()
}


// MARK: - 数据源方法
extension WKHomeViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        //获取数据
        let vm = listViewModel.statusList[indexPath.row]
        
        //创建cell
        let cell = tableView.dequeueReusableCellWithIdentifier(vm.cellID, forIndexPath: indexPath) as! StatusCell
        
        cell.viewModel = vm
        
        //判断是否为最后一条微博开始上拉刷新数据
        if indexPath.row == listViewModel.statusList.count - 1 && !pullupView.isAnimating(){
        
            //开始动画
            pullupView.startAnimating()
            
            //上拉刷新数据
            loadData()
        
        }
        
        //返回cell
        return cell
    }
    
    //计算行高的方法
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        
        return listViewModel.statusList[indexPath.row].rowHeight
    }
    
}
